package com.myx.servlet;

import com.myx.pojo.User;
import com.myx.service.user.UserService;
import com.myx.service.user.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet",value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private final UserService userService=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String username= request.getParameter("uname");
        String password=request.getParameter("upassword");
        String rememberMe = request.getParameter("rememberMe");
        //调用service中的方法
        User user = userService.getUserByUsernameAndPassword(username, password);
        if (rememberMe!=null&&rememberMe.equals("1")){
            //将user对象存到cookie容器中
            //1.创建cookie对象
            Cookie cookie = new Cookie("usernameKey",user.getUsername());
            Cookie cookie2 = new Cookie("passwordKey",user.getPassword());
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24);
            //将服务器中的对象响应到客户端的存储空间中
            response.addCookie(cookie2);
            response.addCookie(cookie);
        }
        System.out.println("user is "+ user);
        // session 临时的保存k-v对数据，默认时间30分钟 作用域可以跨文件
        HttpSession session=request.getSession();
        session.setAttribute("userKey",user);
        //返回一个页面 请求转发/重定向
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }


}
